package org.graffitidiary.activity;

import org.graffitidiary.R;
import org.graffitidiary.bean.FileInfo;
import org.graffitidiary.dialogfragment.EditGraffitiNameFileDialogFragment;
import org.graffitidiary.dialogfragment.SelfDialog;
import org.graffitidiary.framework.ui.ActionBarActivity;
import org.graffitidiary.utils.BitmapUtil;
import org.graffitidiary.utils.ToastUtil;
import org.graffitidiary.view.DrawView;
import org.graffitidiary.view.iosdialog.ActionSheetDialog;
import org.graffitidiary.view.iosdialog.ActionSheetDialog.OnSheetItemClickListener;
import org.graffitidiary.view.iosdialog.ActionSheetDialog.SheetItemColor;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.util.List;

public class MainActivity extends ActionBarActivity implements SeekBar.OnSeekBarChangeListener{
    private static final String TAG = "MainActivity";

    private Bitmap bitmap;
    public static final int NONE = 0;
    public static final int PHOTOHRAPH = 1;// 拍照
    public static final int PHOTOZOOM = 2; // 缩放
    public static final int PHOTORESOULT = 3;// 结果
    public static final String IMAGE_UNSPECIFIED = "image/*";
    public static final String TEMP_JPG_NAME = "temp.jpg";

    private DrawView draw_view;
    private ImageView iv_color_disk;
    private SeekBar progresss;

    String toDraw;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndPermission.with(getApplication())
        .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
        .onGranted(new Action() {
            @Override
            public void onAction(List<String> permissions) {
            }
        })
        .onDenied(new Action() {
            @Override
            public void onAction(List<String> permissions) {
            }
        }).start();

        toDraw = getIntent().getStringExtra("toDraw");
        showBar();
        setBarTitle("画板");
        showBarRightImgBtn();
        setBarRightBackgroundResource(R.drawable.more);
        setBarRight2Img(R.drawable.pigment);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews() {
        draw_view = (DrawView) findViewById (R.id.draw_view);
        draw_view.setOnClickListener(this);
        iv_color_disk = (ImageView) findViewById(R.id.iv_color_disk);
        iv_color_disk.setFocusable(true);
        iv_color_disk.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();

                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    int h = bitmap.getHeight();
                    int w = bitmap.getWidth();
                    System.out.println("w:" + w + ",h:" + h);
                    if((x > 0 && y > 0) && (x < w && y < h)){
                        int color = bitmap.getPixel(x, y);
                        // 如果你想做的更细致的话 可以把颜色值的R G B 拿到做响应的处理
                        int r = Color.red(color);
                        int g = Color.green(color);
                        int b = Color.blue(color);
                        int a = Color.alpha(color);
                        selectColor = Color.rgb(r, g, b);
                        draw_view.setPaintColor(selectColor);
                        setBarColor(selectColor);//设置bar颜色
                    }else{
                        draw_view.setVisibility(View.VISIBLE);
                        showAndHideRight2();
                    }
                }
                return true;
            }
        });
        progresss = (SeekBar) findViewById(R.id.progresss2);
        progresss.setOnSeekBarChangeListener(this);
    }

    boolean isRight2 = true;
    int selectColor;
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.bar_btn_right:
                showMore();
                break;
            case R.id.draw_view:

                break;
            case R.id.bar_btn_right2:
                showAndHideRight2();
                break;
            default:
                break;
        }
    }

    private void showAndHideRight2() {
        if(isRight2){
            iv_color_disk.setVisibility(View.VISIBLE);
            progresss.setVisibility(View.VISIBLE);
            isRight2 = false;
        }else{
            iv_color_disk.setVisibility(View.GONE);
            progresss.setVisibility(View.GONE);
            isRight2 = true;
        }
    }

    private void showMore() {
        new ActionSheetDialog(MainActivity.this)
                .builder()
                .setTitle("更多")
                .addSheetItem("相册颜色", SheetItemColor.Orange,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                openAlbum();
                            }
                        })
                .addSheetItem("清空画板", SheetItemColor.Orange,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                draw_view.clear();
                            }
                        })
                .addSheetItem("保存涂鸦", SheetItemColor.Orange,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                saveGraffiti();
                            }
                        }).show();
    }

    private EditGraffitiNameFileDialogFragment dialogFragment;

    private SelfDialog selfDialog;
    private void saveGraffiti() {
        dialogFragment = new EditGraffitiNameFileDialogFragment(MainActivity.this);
        dialogFragment.show(getFragmentManager(), " BasicInfoDialogFragment");
//        selfDialog = new SelfDialog(MainActivity.this);
//        selfDialog.setTitle("编辑");
//        selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
//            @Override
//            public void onYesClick() {
//                String name = selfDialog.getMsg();
//                if(!TextUtils.isEmpty(name)){
//                    setGraffitiName(name);
//                    selfDialog.dismiss();
//                }else{
//                    ToastUtil.showLongToast("请输入昵称");
//                }
//            }
//        });
//        selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
//            @Override
//            public void onNoClick() {
//                selfDialog.dismiss();
//            }
//        });
//        selfDialog.show();
    }
    /**
     * 设置文件本地名称
     * @param name
     */
    public void setGraffitiName(String name) {
        FileInfo fileInfo = draw_view.save(name);
        if(fileInfo != null){
            if("toDraw".equals(toDraw)){
                Intent data = new Intent();
                data.putExtra("fileInfo", fileInfo);
                setResult(RESULT_OK, data);
                finish();
            } else {
                finish();
            }
        }else{
            ToastUtil.showLongToast("亲请画点东西");
        }
    }

    // 打开相册
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, PHOTOZOOM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {

            if (resultCode == NONE)
                return;
            if (data == null)
                return;
            // 读取相册缩放图片
            if (requestCode == PHOTOZOOM) {
                if (data != null) {
                    startPhotoZoom(data.getData());
                }
            }

            // 处理结果
            if (requestCode == PHOTORESOULT) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    bitmap = extras.getParcelable("data");
                    BitmapUtil.comp(bitmap);
                    iv_color_disk.setImageBitmap(bitmap);
                    iv_color_disk.setVisibility(View.VISIBLE);
                    isRight2 = false;
                }
            }

            super.onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTORESOULT);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        switch (seekBar.getId()){
            case R.id.progresss2:
                draw_view.setPaintStrokeWidth(seekBar.getProgress());
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}